<?php
declare (strict_types = 1);

namespace app\common\middleware;
use thans\jwt\facade\JWTAuth;
use think\Exception;

class outh
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {
            $data=$request->all();
            //dd($data);
            //验证token
            $payload = JWTAuth::auth();

            //验证时间戳
            $this->checkTime($data['timestamps']);

            //验证签名
            $client_sign=$this->sign($data);
//          dd($client_sign);
            $this->checkSign($data['sign'],$client_sign);
            return $next($request);
        }catch (\Exception $e){
            return fail($e->getMessage());
        }


    }


    public function checkTime($time){
        if(!is_numeric($time)){
            throw new Exception('时间戳格式不正确');
        }
        if(time()-$time>6000){
            throw new Exception('请求超时');
        }
    }
    public function checkSign($sign, $client_sign){
        if(!$sign){
            throw new Exception('没有签名');
        }
//        dd($sign,$client_sign);
        if($sign!=$client_sign){
            throw new Exception('签名不正确');
        }
    }

    //生成签名
    public function sign($data){
        # 第一步 参与签名的参数不包括签名本身、不包括token
        unset($data['sign']);
        unset($data['token']);
        # 第二步 按照ASCII排序
        ksort($data);
        //return $data;
        $wait_sign = null;
        foreach ($data as $key=> $value) {
            $wait_sign .= $key.'='.$value.'&';
        }
        # 去除多余的& 符号
        $wait_sign=rtrim($wait_sign,'&');
        return  md5($wait_sign);
    }
}
